import { clearRefreshTokenCookie, setRefreshTokenCookie } from '~/utils/cookie-utils';
import { generateAccessToken, generateRefreshToken } from '~/utils/jwt-utils';
import { forbiddenResponse, useResponseSuccess, useResponseError } from '~/utils/response';

import { queryDatabase } from '~/functions';

// import bcrypt from 'bcrypt';

export default defineEventHandler(async (event) => {
  const { password, username } = await readBody(event);
  if (!password || !username) {
    setResponseStatus(event, 400);
    return useResponseError('BadRequestException', 'Username and password are required');
  }

  // const findUser = MOCK_USERS.find(
  //   (item) => item.username === username && item.password === password,
  // );
  // console.log(findUser);

  // 从数据库查询用户
  let findUser;
  const results = <any[]>(
    await queryDatabase('SELECT * FROM user WHERE username = ? AND password = ?', [username, password])
  );

  if (results.length > 0) {
    // const isPasswordValid = await bcrypt.compare(password, results[0].password);
    // console.log('校验结果：',isPasswordValid);
    // if (isPasswordValid) {
    // 转换数据格式
    findUser = {
      id: results[0].id,
      // password: results[0].password,
      realName: results[0].realName,
      roles: [results[0].roles],
      username: results[0].username,
      homePath: results[0].homePath,
      useremail: results[0].useremail,
      avatar: results[0].avatar,
      enable: results[0].enable,
    };
    // }
  }

  // 如果没有找到用户，提示错误；如果找到了但是enable为false，提示被禁用
  if (!findUser) {
    clearRefreshTokenCookie(event);
    return forbiddenResponse(event, 'Username or Password is incorrect');
  } else if (!findUser.enable) {
    clearRefreshTokenCookie(event);
    return forbiddenResponse(event, 'User is disabled');
  }

  const accessToken = generateAccessToken(findUser);
  const refreshToken = generateRefreshToken(findUser);

  setRefreshTokenCookie(event, refreshToken);

  return useResponseSuccess({
    ...findUser,
    accessToken,
  });
});
